/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


var $j = jQuery.noConflict();

$j(document).ready(function(){
    var servletUrl = "Controller";
    $j.post(servletUrl, {
            type: "onload"  
        }, function (data){
            alert('Test cookies and session: '+data);
        });
});

$j(document).ready(function(){

    /*      Example of hidden block
$j('.signInButton').click(function(){
   $j('.over').fadeIn();
   $j('.inner').click(function(){//make close button and change inner to button close class
       $j('.over').fadeOut();
   });
});
     */
    
    
    
    /*---------------------Autorization and Registration------------------------*/
    /*Login with social site*/
    //check with DB and if true -> loading functional to user and changing block with ...
    var userName, pass, firstName, secondName, socialID, email, registrationDate;
    var servletUrl = "Controller";
    var googleBooksUrl = "GoogleBooks";
    var VkUrl="Vk";
    var userInfo;
    var bookInfo;
    
    
    
    function loadLoggedIn(someName){
        $j.get("ajaxAll.jsp", function(data) {
            data = $j(data);
            $j(".signIn").html($j('#logOut', data).html());
            // JS for loaded button
            $j('#logOutButton').click(function(){
                $j.get("ajaxAll.jsp", function(data) {
                    data = $j(data);
                    $j(".signIn").html($j('#loginBack', data).html());
                });
            });
            $j('.meetingUser').html('Hello, '+someName/*.firstName*/+'!');
        });
    }
    
    function servletDataExchange(whatType,mbsocialID, callback){
        $j.post(servletUrl, {
            type: whatType,
            socialID: mbsocialID
        }, function (data){
            alert('JSON: '+data);
            // userInfo=JSON.parse(data);
            userInfo=JSON.parse(data);
            alert('Name: '+userInfo.firstName);
            callback(userInfo);
        });
    }
    function checkAndGetUserInfo(login, pass, callback){
        $j.post(servletUrl, {
            type: "checknotsocial",
            userlog: login,
            userpass: pass
        }, function (data){
            alert('Result: '+data);
            if (data !="false"){
                //userInfo=JSON.parse(data);
                alert('Name: '+data);
                callback(data);
            //servletDataExchange("notsocial","",loadLoggedIn); 
            } else {
                alert ('Wrong Username or password! Try again');
                $j('#username').val("").focus();
                $j('#pass').val("");
            }
        });
    }
    $j(document).on('click', '#fb', function(){
        servletDataExchange("facebook","id100fb",loadLoggedIn);
    });
    $j(document).on('click', '#tw', function(){
        servletDataExchange("twitter","id200tw",loadLoggedIn);
    });
    
    $j(document).on('click', '#gPlus', function(){
        servletDataExchange("googlePlus","id400gP",loadLoggedIn);
    });
    
    /*Login with paragraphs in the form signIn*/

    $j(document).on('focusout', '#username', function(){// focus out from pass and userName -> Check string length -> printf Hi man
        userName = $j('#username').val();
        if(userName.length <= 0){ 
            alert('Enter your name');
        }
    });
    
    $j(document).on('focusout', '#pass', function(){
        pass = $j('#pass').val();
        if(pass.length <= 0){
            alert('Enter your pass');
        }
    });
    
    
    $j(document).on('click', '.signInButton', function(){
        if (userName.length>0 && pass.length>0){
            checkAndGetUserInfo(userName, pass,loadLoggedIn);
        }else{
            alert('Please, enter name and password!');
        }
    });
    
    /*Registration*/
    var Error="notAllFields";
    
    function clearInput(){
        $j('.registrationBlock').fadeIn();
        $j('#login').val("");
        $j('#password').val("");
        $j('#firstName').val("");
        $j('#lastName').val("");
        $j('#eMail').val("");
        $j('#confirmPassword').val(""); 
    }
    
    $j(document).on('click', '#registrationButton', function(){
        clearInput();
        $j('#CancelRegistration').click(function(){//make close button and change inner to button close class
            $j('.registrationBlock').fadeOut();
        });
    });
    
    function checkInputs(){
        var flag1=true, flag2=true, flag3=true, flag4=true;
        if ($j('#login').val().length <= 0 || $j('#password').val().length <= 0 || $j('#firstName').val().length <= 0){
            flag1=false;
        }
        if ($j('#lastName').val().length <= 0 || $j('#eMail').val().length <= 0){
            flag2=false;
        }
        if ($j('#password').val() != $j('#confirmPassword').val()){
            flag3=false;
            Error='password and confirmed password fields are missmatch!';
        }
        /*e-mail validation*/
        
        var reg = new RegExp("[0-9a-z_]+@[0-9a-z_^.]+\\.[a-z]{2,3}", 'i');
        if (!reg.test($j('#eMail').val())) {
            Error='E-mail is incorrect. Try again!';
            flag4=false;
        } 
        
        if (flag1 && flag2&& flag3 && flag4){
            return true;
        } else {
            return false;
        }
    }
    
    $j(document).on('click', '#toCompleteRegistrationButton', function(){
        if (checkInputs()){
            $j.post(servletUrl, {
                type: "registration",
                userlog: $j('#login').val(),
                userpass: $j('#password').val(),
                username:  $j('#firstName').val() ,
                usersurname: $j('#lastName').val() ,
                useremail: $j('#eMail').val()
            }, function (data){
                alert('Result: '+data);
            });
            $j('.registrationBlock').fadeOut();
        } else {
            switch (Error){
                case "notAllFields":
                    alert('Please enter all fields!');
                    clearInput();
                    break;
                case "E-mail is incorrect. Try again!":
                    alert(Error);
                    $j('#eMail').val("");
                    break;
                default:
                    alert (Error);
                    $j('#confirmPassword').val("");
                    $j('#password').val("");
                    Error = "notAllFields";
            }           
        }
    });
    //$j('.signIn').html(""); // clear signIn div
    //add ajax
    
    /*---------------------Books Manipulation------------------------*/
    /****Adding Book****/
    $j(document).on('click', '#addBookButtonMain', function(){
        $j('.addBooksBlock').fadeIn();
        $j('#CancelBook').click(function(){//make close button and change inner to button close class
            $j('.addBooksBlock').fadeOut();
        });
        
    });
    
    function checkBooks(){
        /*ISBN = 10 symbols???*/
        var reg= new RegExp("[0-9]{10,13}");
        if (!reg.test($j('#ISBN').val()) || $j('#Title').val().length <=0 || $j('#Description').val().length <=0 || $j('#NumberOfPages').val().length <=0){
            return false;
        }
        return true;
    }
    
    $j(document).on('click', '#AddBook', function(){
        $j.post(googleBooksUrl, {
            isbn: $j('#ISBN').val()
        }, function (notParsedRecvObject){
            alert(notParsedRecvObject);
            var recvObject= JSON.parse (notParsedRecvObject);
            alert("JSON: isbn = "+recvObject.items[0].volumeInfo.industryIdentifiers[1].identifier +";\n\
                title "+ recvObject.items[0].volumeInfo.title+ "; \n\ author" +recvObject.items[0].volumeInfo.authors +";\n\
                description"+recvObject.items[0].volumeInfo.description+"; pages = "+ recvObject.items[0].volumeInfo.pageCount+";\n\
                image link = "+recvObject.items[0].volumeInfo.imageLinks.thumbnail);
            $j.post(servletUrl, {
                type : "addingNewBook",
                isbn : recvObject.items[0].volumeInfo.industryIdentifiers[1].identifier,
                title : recvObject.items[0].volumeInfo.title,
                authors : recvObject.items[0].volumeInfo.authors,
                description : recvObject.items[0].volumeInfo.description,
                numberOfPages : recvObject.items[0].volumeInfo.pageCount,
                image : recvObject.items[0].volumeInfo.imageLinks.thumbnail
            }, function (data){
                alert(data);
            });
        });
    });

    /***Change Books View***/
    var count=10;
    $j(document).on('click', '#gridButton', function(){
        $j('#content').attr('class','');
        $j('#content').addClass('grid');
        count=10;
    });
    $j(document).on('click', '#smallListButton', function(){
        $j('#content').attr('class','');
        $j('#content').addClass('smallList');
        count=20;
    });
    $j(document).on('click', '#bigListButton', function(){
        $j('#content').attr('class','');
        $j('#content').addClass('bigList');
        count=10;
    });
    
    var bookAmount = $j('.bookDisplay').size();
    var page = 1;    
        
    function displayParsedInfo(book){
        var temporary = "<div class='leftBookDisplay'> "
        +"<div class='image'><img src='"+book.image+"' /></div>" 
        +"<div class='rating'><h4>"+book.rating+"</h4></div></div>"
        +"<div class='rightBookDisplay'>"
        +"<div class='title'>"+book.title+"</div>"
        +"<div class='descp'>"+book.description+"</div>"
        +"<div class='isbn'>"+book.ISBN+"</div></div>";
        return temporary;
    }
    $j(document).on('click', '#left', function(){
        $j.post(servletUrl, {
            type: "previousBooks",
            pageNumber: page,
            amount: count
        }, function (data){
            var newPageBooks = data.split(';');
            var parsedBooks = new Array(newPageBooks.length);
            $j('#contentWrapper').html("");
            for(var i = 0;i < newPageBooks.length; i++){
                parsedBooks[i] = JSON.parse(newPageBooks[i]);
                $j('#contentWrapper').append('<div class="bookDisplay">' + displayParsedInfo(parsedBooks[i]) + '</div>');
            }
        });
    });  
    
    
    
});//after page was loaded
